// app/controller/users.js
const Controller = require('egg').Controller;
// 使用模糊查询需要先引入Op
const seq = require('sequelize');
const Op = seq.Op;
function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class UserController extends Controller {
    constructor(ctx){
        super(ctx)
         this.ruls={
            name: {
                type: 'string',
                min:5,
                max:20	// 年龄范围0-120
              },	// 自定义的校验规则
            // password: 'password',	// 自带的校验规则
            // sex: ['men', 'women'],	// 性别是men或者women
            age: {
              type:'number',			// 年龄范围0-120
              min: 1,
              max: 120
            }
        }
    }
  async index() {
    const ctx = this.ctx;
    const size=toInt(ctx.query.size)
    let current=toInt(ctx.query.current)
    const where=ctx.query.username?{
      username:{
        [Op.like]: `%${ctx.query.username}%`
      }
    }:{}
    if (current<=0){
      current=1
    }
    let count = await ctx.model.User.count({where});
    const query = {
      limit: size,
      offset: (current-1)*size,
      attributes: {exclude: ['password']},
      where:{
        ...where,
      }
    };
    let list=await ctx.model.User.findAll(query)
    ctx.body = {
      code:0,
      data:list,
      count
    };
  }

  async show() {
    const ctx = this.ctx;
    const query = {
      attributes: {exclude: ['password']},
      where:{
        id:ctx.params.id
      }
    };
    let {dataValues}=await ctx.model.User.findOne(query)
    ctx.helper.success(ctx,{data:dataValues})
  }

  async create() {
    const ctx = this.ctx;
    const { username, age,password,status } = ctx.request.body;
    const pws=await ctx.helper.genSaltPassword(password)
    const userinfo = await ctx.model.User.findOne({
      where:{
        username
      }
    });
    if (!userinfo){
      const user = await ctx.model.User.create({username, age,password:pws,status});
      ctx.status = 200;
      ctx.body = user;
    }else {
      ctx.status = 200;
      ctx.body = '用户名存在';
    }
  }

  async update() {
    const ctx = this.ctx;
    const data=ctx.query
    const id = toInt(data.id);
    const user = await ctx.model.User.findByPk(id);
    if (!user) {
      ctx.status = 404;
      return;
    }

    const { name, age } = ctx.request.body;
    const errors = this.app.validator.validate(this.ruls, ctx.request.body);
    await user.update(data);
    ctx.body =errors??user;
  }

  async destroy() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const user = await ctx.model.User.findByPk(id);
    if (!user) {
      ctx.status = 404;
      return;
    }
    const res=await user.destroy(id);
    ctx.helper.success(ctx,{data:{message:'删除成功'}});
  }
}

module.exports = UserController;
